import 'dart:async';
import 'package:flutter/material.dart';
import 'package:palyer/app/components/toast_widget.dart';
import 'package:tray_manager/tray_manager.dart';

class MangerPage extends StatefulWidget {
  const MangerPage({Key? key}) : super(key: key);

  @override
  _MangerPageState createState() => _MangerPageState();
}

class _MangerPageState extends State<MangerPage> with TrayListener {
  final TrayManager _trayManager = TrayManager.instance;

  final String _iconPathWin = 'assets/image/Kiss_me.ico';

  Timer? _timer;

  bool _hasIcon = false;

  List<MenuItem> items = [
    MenuItem(
      label: '语文',
      toolTip: '语文是一门很有意思的学科',
      icon: 'assets/image/Kiss_me.ico',
      submenu: Menu(items: [
        MenuItem(label: '草泥马'),
        MenuItem(label: '我是你爸爸'),
      ]),

    ),
    MenuItem(label: '数学', toolTip: '躲不掉的'),
    MenuItem(
      label: '英语',
    ),
    MenuItem(
      key: 'science',
      label: '理科',
    ),
    MenuItem(
      key: 'arts',
      label: '文科',
    ),
  ];

  @override
  void initState() {
    trayManager.addListener(this);
    _iconFlash();
    super.initState();
  }

  @override
  void onTrayIconRightMouseDown() async {
    await _trayManager.popUpContextMenu();
  }

  @override
  void onTrayMenuItemClick(MenuItem menuItem) {
    AppToast.show('你选择了${menuItem.label}');
  }

  // @override
  // void onTrayIconMouseDown() {
  //   windowManager.show(); // 该方法来自window_manager插件
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
        actions: [
          IconButton(
              onPressed: _generateToolTip,
              icon: const Icon(Icons.turned_in_rounded))
        ],
      ),
      // body: ,
    );
  }

  void _generateToolTip() async {
    await _trayManager.setToolTip('你想干嘛😒');
    await _trayManager.setContextMenu(Menu(items: items));
  }

  void _iconFlash() {
    _generateToolTip();
    _timer = Timer.periodic(const Duration(milliseconds: 600), (timer) async {
      if (_hasIcon) {
        await _trayManager.setIcon(_iconPathWin);
      } else {
        await _trayManager.setIcon(
          'assets/image/icon.ico',
        );
      }
      _hasIcon = !_hasIcon;
      setState(() {});
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    trayManager.removeListener(this);
    _trayManager.destroy();
    super.dispose();
  }
}
